package com.lurencun.service.autoupdate.internal;

import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.lurencun.service.autoupdate.ResponseParser;
import com.lurencun.service.autoupdate.Version;

import java.text.SimpleDateFormat;
import java.util.Date;

/*
{
    "updateInfo":{
        "appName": "android-updater",
        "versionCode": "2",
        "versionName": "2.0",
        "apkUrl": "http://helloworld-snowdream.herokuapp.com/explorer-2.0.apk",
        "releaseNote": "升级提示:\n1.升级提示\n2.升级提示\n3.升级提示",
		"releaseTime":"2013-04-23 12:01:45"
    }
}
{"msg":"获取成功","data":{"id":"1","appName":"app12","versionCode":"app12","versionName":"1.012","app_install":"40281d815ec401d7015ec412055b0004","releaseNote":"1323123222222","releaseTime":1506528069000,"apkUrl":"http://120.27.10.29/security/upload/app/201709280001086pIj56UB.xls"},"status":1}

 */
public class SimpleJSONParser implements ResponseParser {

    @Override
    public Version parser(String response) {
        Version version = null;
        try {
            Log.d("ckf", "response=== " + response);
            JSONTokener jsonParser = new JSONTokener(response);
            JSONObject versionObject = (JSONObject) jsonParser.nextValue();
            versionObject = versionObject.getJSONObject("data");
            int versionCode = Integer.valueOf(versionObject.getString("versionCode"));
//            int versionCode = 1;

            String versionName = versionObject.getString("appName");
            String releaseNote = versionObject.getString("releaseNote");
            String releaseUrl = versionObject.getString("apkUrl");
            String releaseTime = versionObject.getString("releaseTime");
            if (!TextUtils.isEmpty(releaseTime)){
                releaseTime= getStringDate(Long.valueOf(releaseTime));
            }
            String appName = versionObject.getString("appName");
            version = new Version(versionCode, versionName, appName, releaseNote, releaseUrl, releaseTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public  String getStringDate(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String dateString = formatter.format(time);
        return dateString;
    }

//        {"id":"1","appName":"app12",
// "appCode":"app1","versionCode":"3"
//                ,"app_install":"2c9f74eb5fbe9816015fbeb4e3020008","releaseNote":"\b测试",
//                "releaseTime":1510738267000,
//                "apkUrl":"http://120.27.10.29/security//security/upload/null/20171115/20171115160406adFbhuTP.apk"}
//    ,"status":1}

}
